package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.dto.OrderDTO;
import com.itheima.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/order")
@Api("用户端预约功能相关接口")
public class OrderController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private RedisTemplate redisTemplate;

	@GetMapping("/findById")
	@ApiOperation("根据id查询预约信息")
	public Result findById(Integer id) {
		log.info("根据id查询预约信息");
		Order order = orderService.findById(id);
		return new Result(true, "查询成功", order);
	}

	@PostMapping("/submitOrder")
	@ApiOperation("用户体检预约")
	public Result submitOrder(@RequestBody OrderDTO orderDTO) {
		log.info("用户提交预约信息");
		// 校验预定验证码的合法性
		Integer validateCode = (Integer) redisTemplate.opsForValue()
				.get(RedisMessageConstant.SENDTYPE_ORDER + "_" + orderDTO.getTelephone());
		if (validateCode == null ||
				Integer.compare(Integer.valueOf(orderDTO.getValidateCode()), validateCode) != 0) {
			return new Result(false, MessageConstant.VALIDATECODE_ERROR);
		}
		// 提交预约信息并获取预约记录数
		Integer recordCount = orderService.submitOrder(orderDTO);

		// 返回预约成功结果和预约编号
		return new Result(true, MessageConstant.ORDER_SUCCESS, recordCount);

	}
}
